import {
  Controller,
  Get,
  Post,
  Body,
  UseGuards,
  ValidationPipe,
  HttpCode,
  HttpStatus,
  Param,
  NotFoundException,
} from '@nestjs/common';
import { UserService } from './user.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../auth/decorators/user.decorator';
import { CreateUserDto } from './dto/create-user.dto';
import { LoginDto } from './dto/login.dto';
import { AjaxResult } from '../common/utils/ajax-result';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { }

  @Post('register')
  @HttpCode(HttpStatus.CREATED)
  async register(@Body(ValidationPipe) createUserDto: CreateUserDto) {
    const result = await this.userService.register(createUserDto);
    return AjaxResult.success(result, '注册成功');
  }

  @Post('login')
  @HttpCode(HttpStatus.OK)
  async login(@Body(ValidationPipe) loginDto: LoginDto) {
    const result = await this.userService.login(loginDto);
    return AjaxResult.success(result, '登录成功');
  }

  @UseGuards(JwtAuthGuard)  // 使用JWT守卫
  @Get('profile')
  async getProfile(@CurrentUser() user: any) {
    // 此时的 user 已经经过 JwtStrategy 的验证
    // 确保了 token 中的用户确实存在
    const result = await this.userService.findById(user.userId);
    return AjaxResult.success(result);
  }

  @Get('/:email')
  async getUser(@Param('email') email: string) {
    console.log(email);

    const user = await this.userService.findByEmail(email);
    if (!user) {
      throw new NotFoundException('用户不存在');
    }
    return AjaxResult.success(user);
  }

  @Post('send-code')
  @HttpCode(HttpStatus.OK)
  async sendCode(@Body('email') email: string) {
    await this.userService.sendVerificationCode(email);
    return AjaxResult.success(null, '验证码已发送');
  }

  @Post('reset-password')
  @HttpCode(HttpStatus.OK)
  async resetPassword(
    @Body() data: { token: string; newPassword: string },
  ) {
    await this.userService.resetPassword(data.token, data.newPassword);
    return AjaxResult.success(null, '密码重置成功');
  }
} 